package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyTest {
    public static MyInterface createProxy(MyInterface myClass){
        MyInterface myClass1 = (MyInterface) Proxy.newProxyInstance(myClass.getClass().getClassLoader(),
                new Class[]{MyInterface.class}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                       if(method.getName() == "dance" || method.getName() == "sing"){
                           long times = System.currentTimeMillis();
                           Object rs = method.invoke(myClass, args);
                           Thread.sleep(1000);
                           long times2 = System.currentTimeMillis();
                           System.out.println("耗时:" + (times2-times) / 1000);
                           return rs;
                       }else{
                           Object rs = method.invoke(myClass, args);
                           return rs;
                       }
                    }
                });
        return myClass1;
    }

    public static void main(String[] args) {
        MyInterface class1 = new MyClass();
        MyInterface class2 = ProxyTest.createProxy(class1);
        class2.dance();
        class2.sing();
    }
}
